package com.ruoyi.distributionPoster.service.impl;

import java.util.Base64;
import java.util.Date;
import java.util.List;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.distributor.domain.DistributionUser;
import com.ruoyi.distributor.service.IDistributionUserService;
import com.ruoyi.distributionPoster.domain.DistributionPoster;
import com.ruoyi.distributionPoster.domain.QRCodeRequest;
import com.ruoyi.distributionPoster.domain.QRCodeResult;
import com.ruoyi.distributionPoster.mapper.DistributionPosterMapper;
import com.ruoyi.distributionPoster.service.IDistributionPosterService;
import com.ruoyi.goods.domain.Goods;
import com.ruoyi.goods.service.IGoodsService;
import com.ruoyi.distributionPoster.util.QRCodeGenerator;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 分销海报记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-11-21
 */
@Service
public class DistributionPosterServiceImpl implements IDistributionPosterService
{
    private static final Logger log = LoggerFactory.getLogger(DistributionPosterServiceImpl.class);

    @Autowired
    private DistributionPosterMapper distributionPosterMapper;

    @Autowired
    private IDistributionUserService distributionUserService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private QRCodeGenerator qrCodeGenerator;

    @Value("${qrcode.base-url:https://maomingdongxinzhizun.cn}")
    private String qrCodeBaseUrl;

    @Value("${qrcode.expire-days:7}")
    private Integer qrCodeExpireDays;

    /**
     * 生成包含分销员信息和商品信息的二维码
     */
    @Override
    public QRCodeResult generateProductQRCode(QRCodeRequest qrCodeRequest) {
        try {
            log.info("开始生成分销二维码 - 分销员ID: {}, 商品ID: {}, 版本类型: {}, 时间戳: {}",
                    qrCodeRequest.getDistributorId(), qrCodeRequest.getGoodsId(),
                    qrCodeRequest.getVersionType(), System.currentTimeMillis());

            log.info("验证分销员信息 - 分销员ID: {}", qrCodeRequest.getDistributorId());
            DistributionUser distributor = validateDistributor(qrCodeRequest.getDistributorId());

            log.info("验证商品信息 - 商品ID: {}", qrCodeRequest.getGoodsId());
            Goods goods = validateGoods(qrCodeRequest.getGoodsId());

            log.info("生成场景ID - 分销员ID: {}, 商品ID: {}, SKU ID: {}", qrCodeRequest.getDistributorId(), qrCodeRequest.getGoodsId(), qrCodeRequest.getSkuId());
            String sceneId = generateSceneId(qrCodeRequest.getDistributorId(), qrCodeRequest.getGoodsId(), qrCodeRequest.getSkuId());

            log.info("生成二维码内容 - 分销员ID: {}, 商品ID: {}, SKU ID: {}", qrCodeRequest.getDistributorId(), qrCodeRequest.getGoodsId(), qrCodeRequest.getSkuId());
            String qrContent = generateQRContent(distributor, goods, qrCodeRequest);

            log.info("生成二维码图片数据 - 分销员ID: {}, 商品ID: {}, SKU ID: {}", qrCodeRequest.getDistributorId(), qrCodeRequest.getGoodsId(), qrCodeRequest.getSkuId());
            String qrCodeData = generateQRCodeImage(qrContent, qrCodeRequest);

            log.info("查找是否已存在相同scene_id的记录 - scene_id: {}", sceneId);
            DistributionPoster existingPoster = distributionPosterMapper.selectDistributionPosterBySceneId(sceneId);
            log.info("检查是否已存在相同scene_id的记录 - scene_id: {}", sceneId);
            DistributionPoster poster;
            if (existingPoster != null) {
                // 如果存在则更新现有记录
                poster = updateExistingPoster(existingPoster, qrCodeRequest, qrContent, qrCodeData);
            } else {
                // 如果不存在则创建新记录
                poster = createPosterRecord(distributor, goods, qrCodeRequest, qrContent, qrCodeData, sceneId);
            }

            log.info("返回结果 - 分销员ID: {}, 商品ID: {}, SKU ID: {}", qrCodeRequest.getDistributorId(), qrCodeRequest.getGoodsId(), qrCodeRequest.getSkuId());
            return buildQRCodeResult(poster, qrContent, qrCodeData);

        } catch (Exception e) {
            log.error("生成商品二维码失败", e);
            throw new ServiceException("生成二维码失败：" + e.getMessage());
        }
    }


//    /**
//     * 生成包含分销员信息和商品信息的二维码
//     */
//    @Override
//    public QRCodeResult generateProductQRCode(QRCodeRequest qrCodeRequest) {
//        try {
//            // 1. 验证分销员信息 通过传递的分销员ID验证分销员信息
//            DistributionUser distributor = validateDistributor(qrCodeRequest.getDistributorId());
//
//            // 2. 验证商品信息 通过传递的商品ID验证商品信息
//            Goods goods = validateGoods(qrCodeRequest.getGoodsId());
//
//            // 3. 生成场景ID 生成一个唯一的场景ID，通常包含分销员ID、商品ID和SKU ID等信息
//            String sceneId = generateSceneId(qrCodeRequest.getDistributorId(), qrCodeRequest.getGoodsId(), qrCodeRequest.getSkuId());
//
////            // 4. 检查是否已存在相同scene_id的记录
////            DistributionPoster existingPoster = checkExistingPoster(sceneId, qrCodeRequest);
////
////            // 如果已存在相同scene_id的记录，则生成二维码内容并返回
////            if (existingPoster != null) {
////                // 生成二维码内容 通过sceneId生成二维码内容，因为现有记录可能已经过期或无效
////                String qrContent = generateQRContent(distributor, goods, qrCodeRequest);
////                // 构建QRCodeResult对象并返回（使用数据库中的二维码数据）
////                return buildQRCodeResult(existingPoster, qrContent, existingPoster.getQrCodeData());
////            }
//
//            // 5. 生成二维码内容
//            String qrContent = generateQRContent(distributor, goods, qrCodeRequest);
//
//            // 6. 生成二维码图片数据（Base64编码）
//            String qrCodeData = generateQRCodeImage(qrContent, qrCodeRequest);
//
//            // 7. 创建海报记录（将二维码图片数据保存到数据库）
//            DistributionPoster poster = createPosterRecord(distributor, goods, qrCodeRequest, qrContent, qrCodeData, sceneId);
//
//            // 8. 返回结果
//            return buildQRCodeResult(poster, qrContent, qrCodeData);
//
//        } catch (Exception e) {
//            log.error("生成商品二维码失败", e);
//            throw new ServiceException("生成二维码失败：" + e.getMessage());
//        }
//    }
//



    /**
     * 验证分销员信息
     */
    private DistributionUser validateDistributor(Long distributorId) {
        DistributionUser distributor = distributionUserService.selectDistributionUserByDistributorId(distributorId);
        if (distributor == null) {
            throw new ServiceException("分销员信息不存在");
        }
        if (!"1".equals(distributor.getAuthStatus())) {
            throw new ServiceException("分销员未审核通过");
        }
        if (!"0".equals(distributor.getStatus())) {
            throw new ServiceException("分销员状态异常");
        }
        return distributor;
    }

    /**
     * 验证商品信息
     */
    private Goods validateGoods(Long goodsId) {
        Goods goods = goodsService.selectGoodsByGoodsId(goodsId);
        if (goods == null) {
            throw new ServiceException("商品信息不存在");
        }
        // 这里可以添加更多的商品状态验证
        return goods;
    }

    /**
     * 生成场景ID
     */
    private String generateSceneId(Long distributorId, Long goodsId, Long skuId) {
        // 构建场景ID
        StringBuilder sceneIdBuilder = new StringBuilder();
        // 添加商品ID、分销员ID和SKU ID
        sceneIdBuilder.append("goods_").append(goodsId)
                      .append("_dis_").append(distributorId);

        if (skuId != null) {
            sceneIdBuilder.append("_sku_").append(skuId);
        }

        return sceneIdBuilder.toString();
    }

    /**
     * 检查是否已存在相同scene_id的记录
     */
    private DistributionPoster checkExistingPoster(String sceneId, QRCodeRequest qrCodeRequest) {
        // 查询是否存在相同参数的二维码记录
//        DistributionPoster existingPoster = distributionPosterMapper.selectDistributionPosterBySceneId(sceneId);
//
//        if (existingPoster != null) {
//            // 检查记录是否有效且未过期
//            if ("0".equals(existingPoster.getStatus()) &&
//                existingPoster.getExpireTime() != null &&
//                existingPoster.getExpireTime().after(new Date())) {
//
//                // 更新生成次数
//                existingPoster.setGenerateCount(existingPoster.getGenerateCount() + 1);
//                existingPoster.setUpdateTime(new Date());
//                distributionPosterMapper.updateDistributionPoster(existingPoster);
//
//                log.info("找到有效的现有海报记录，sceneId: {}", sceneId);
//                return existingPoster;
//            } else if (existingPoster.getExpireTime() != null &&
//                      existingPoster.getExpireTime().before(new Date())) {
//                // 记录已过期，标记为无效
//                existingPoster.setStatus("2"); // 过期状态
//                existingPoster.setUpdateTime(new Date());
//                distributionPosterMapper.updateDistributionPoster(existingPoster);
//                log.info("海报记录已过期，sceneId: {}", sceneId);
//            }
//        }

        return null;
    }

    /**
     * 生成二维码内容
     * @param distributor 分销员信息
     * @param goods 商品信息
     * @param qrCodeRequest 二维码生成请求参数
     *
     */
    private String generateQRContent(DistributionUser distributor, Goods goods, QRCodeRequest qrCodeRequest) {
        // 构建小程序路径或H5链接
        StringBuilder contentBuilder = new StringBuilder();

        // 如果是小程序二维码
        // 例如：pages/goods/detail?goodsId=xxx&distributorId=xxx

        if ("miniProgram".equals(qrCodeRequest.getFormat()) || StringUtils.isEmpty(qrCodeRequest.getFormat())) {
            // 实际路径：subpackageMall/pages/mall/product/detail?distributorId=31&goodsId=79
            contentBuilder.append(qrCodeBaseUrl)
                    .append("/miniApp/distribution");

            // 根据versionType添加对应的路径
            if ("test".equals(qrCodeRequest.getVersionType())) {
                contentBuilder.append("/test");
            } else if ("development".equals(qrCodeRequest.getVersionType())) {
                contentBuilder.append("/development");
            }

            contentBuilder.append("/subpackageMall/pages/mall/product/detail")
                    .append("?goodsId=").append(goods.getGoodsId())
                    .append("&distributorId=").append(distributor.getDistributorId());

//                    .append("&distributorCode=").append(distributor.getDistributorCode());

            // 添加SKU_ID
            if (qrCodeRequest.getSkuId() != null) {
                contentBuilder.append("&skuId=").append(qrCodeRequest.getSkuId());
            }
            // 添加自定义参数
            if (StringUtils.isNotEmpty(qrCodeRequest.getCustomParams())) {
                contentBuilder.append("&").append(qrCodeRequest.getCustomParams());
            }
        } else {
            // H5链接格式
            // 例如：goods/detail/79?distributorId=31&distributorCode=DIST001
            contentBuilder.append(qrCodeBaseUrl)
                    .append("/goods/detail/")
                    .append(goods.getGoodsId())
                    .append("?distributorId=").append(distributor.getDistributorId())
                    .append("&distributorCode=").append(distributor.getDistributorCode());

            if (qrCodeRequest.getSkuId() != null) {
                contentBuilder.append("&skuId=").append(qrCodeRequest.getSkuId());
            }
        }

        return contentBuilder.toString();
    }

    /**
     * 生成二维码图片数据并返回Base64编码
     */
    private String generateQRCodeImage(String qrContent, QRCodeRequest qrCodeRequest) {
        // 获取二维码图片尺寸, 默认为300x300
        int width = qrCodeRequest.getWidth() != null ? qrCodeRequest.getWidth() : 300;
        int height = qrCodeRequest.getHeight() != null ? qrCodeRequest.getHeight() : 300;

        // 确保尺寸在合理范围内（100-1000像素）
        width = Math.max(100, Math.min(1000, width));
        height = Math.max(100, Math.min(1000, height));

        try {
            // 生成二维码字节数组
            byte[] qrCodeBytes = qrCodeGenerator.generateQRCodeBytes(qrContent, width, height);

            // 将字节数组转换为Base64编码
            String base64Image = Base64.getEncoder().encodeToString(qrCodeBytes);

            // 返回Base64格式的图片数据
            return "data:image/png;base64," + base64Image;

        } catch (Exception e) {
            log.error("生成二维码图片失败", e);
            throw new ServiceException("生成二维码图片失败: " + e.getMessage());
        }
    }


    /**
     * 创建海报记录
     */
    private DistributionPoster createPosterRecord(DistributionUser distributor, Goods goods,
                                                  QRCodeRequest qrCodeRequest, String qrContent, String qrCodeData, String sceneId) {
        DistributionPoster poster = new DistributionPoster();

        // 设置基本信息
        poster.setDistributorId(distributor.getDistributorId()); // 分销员ID
        poster.setGoodsId(goods.getGoodsId()); // 商品ID
        poster.setSkuId(qrCodeRequest.getSkuId()); // SKU_ID 可空
        poster.setPosterType(qrCodeRequest.getPosterType()); // 商品海报类型
        poster.setQrCodeData(qrCodeData); // 存储Base64编码的二维码图片数据
        poster.setSceneId(sceneId);

        // 设置过期时间
        Date expireTime = DateUtils.addDays(new Date(), qrCodeExpireDays);
        poster.setExpireTime(expireTime);

        // 设置状态
        poster.setStatus("0"); // 有效
        poster.setViewCount(0L); // 访问次数
        poster.setGenerateCount(1L); // 生成次数
        poster.setShareCount(0L); // 分享次数
        poster.setConversionCount(0L); // 转化次数

        // 设置创建信息
        poster.setCreateBy(SecurityUtils.getUsername()); // 创建人
        poster.setCreateTime(new Date()); // 创建时间

        // 插入记录
        int result = distributionPosterMapper.insertDistributionPoster(poster);
        if (result <= 0) {
            throw new ServiceException("创建海报记录失败");
        }

        return poster;
    }

    /**
     * 更新现有的海报记录
     */
    private DistributionPoster updateExistingPoster(DistributionPoster existingPoster,
                                                   QRCodeRequest qrCodeRequest,
                                                   String qrContent,
                                                   String qrCodeData) {
        // 更新二维码数据和其他相关信息
        existingPoster.setQrCodeData(qrCodeData); // 二维码图片数据
        existingPoster.setUpdateTime(new Date()); // 更新时间
        existingPoster.setUpdateBy(SecurityUtils.getUsername()); // 更新人

        // 更新过期时间
        Date expireTime = DateUtils.addDays(new Date(), qrCodeExpireDays);
        existingPoster.setExpireTime(expireTime); // 过期时间

        // 重置状态为有效
        existingPoster.setStatus("0"); // 有效

        // 增加生成次数
        existingPoster.setGenerateCount(existingPoster.getGenerateCount() + 1); // 生成次数

        // 更新数据库记录
        int result = distributionPosterMapper.updateDistributionPoster(existingPoster);
        if (result <= 0) {
            throw new ServiceException("更新海报记录失败");
        }

        return existingPoster;
    }

    /**
     * 构建返回结果
     */
    private QRCodeResult buildQRCodeResult(DistributionPoster poster, String qrContent, String qrCodeData) {
        // 构建返回结果对象
        QRCodeResult result = new QRCodeResult();

        result.setPosterId(poster.getPosterId()); // 海报ID
        result.setDistributorId(poster.getDistributorId()); // 分销员ID

        // 获取分销员信息
        DistributionUser distributor = distributionUserService.selectDistributionUserByDistributorId(poster.getDistributorId());
        if (distributor == null) {
            throw new ServiceException("分销员不存在，distributorId: " + poster.getDistributorId());
        }
        result.setDistributorCode(distributor.getDistributorCode()); // 分销员编号
        result.setGoodsId(poster.getGoodsId()); // 商品ID

        result.setQrCodeData(qrCodeData); // 返回Base64编码的二维码图片数据
        result.setQrContent(qrContent); // 二维码内容

        result.setExpireTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", poster.getExpireTime())); // 过期时间
        result.setStatus("success"); // 返回成功
        return result;
    }

    /**
     * 查询分销海报记录
     *
     * @param posterId 分销海报记录主键
     * @return 分销海报记录
     */
    @Override
    public DistributionPoster selectDistributionPosterByPosterId(Long posterId)
    {
        return distributionPosterMapper.selectDistributionPosterByPosterId(posterId);
    }

    /**
     * 查询分销海报记录列表
     *
     * @param distributionPoster 分销海报记录
     * @return 分销海报记录
     */
    @Override
    public List<DistributionPoster> selectDistributionPosterList(DistributionPoster distributionPoster)
    {
        return distributionPosterMapper.selectDistributionPosterList(distributionPoster);
    }

    /**
     * 新增分销海报记录
     *
     * @param distributionPoster 分销海报记录
     * @return 结果
     */
    @Override
    public int insertDistributionPoster(DistributionPoster distributionPoster)
    {
        distributionPoster.setCreateTime(DateUtils.getNowDate());
        return distributionPosterMapper.insertDistributionPoster(distributionPoster);
    }

    /**
     * 修改分销海报记录
     *
     * @param distributionPoster 分销海报记录
     * @return 结果
     */
    @Override
    public int updateDistributionPoster(DistributionPoster distributionPoster)
    {
        distributionPoster.setUpdateTime(DateUtils.getNowDate());
        return distributionPosterMapper.updateDistributionPoster(distributionPoster);
    }

    /**
     * 批量删除分销海报记录
     *
     * @param posterIds 需要删除的分销海报记录主键
     * @return 结果
     */
    @Override
    public int deleteDistributionPosterByPosterIds(Long[] posterIds)
    {
        return distributionPosterMapper.deleteDistributionPosterByPosterIds(posterIds);
    }

    /**
     * 删除分销海报记录信息
     *
     * @param posterId 分销海报记录主键
     * @return 结果
     */
    @Override
    public int deleteDistributionPosterByPosterId(Long posterId)
    {
        return distributionPosterMapper.deleteDistributionPosterByPosterId(posterId);
    }

    /**
     * 清理过期分销海报记录
     *
     * @return 清理结果信息
     */
    @Override
    public String cleanExpiredDistributionPosters() {
        try {
            // 1. 查询所有过期记录
            List<DistributionPoster> expiredPosters = distributionPosterMapper.selectExpiredDistributionPosters();

            if (expiredPosters.isEmpty()) {
                log.info("未发现过期分销海报记录");
                return "未发现过期分销海报记录";
            }

            // 2. 提取过期记录的ID
            Long[] posterIds = expiredPosters.stream()
                    .map(DistributionPoster::getPosterId)
                    .toArray(Long[]::new);

            // 3. 批量删除过期记录
            int deletedCount = distributionPosterMapper.deleteExpiredDistributionPosters(posterIds);

            String result = String.format("成功清理过期分销海报记录 %d 条", deletedCount);
            log.info(result);

            return result;

        } catch (Exception e) {
            String errorMsg = "清理过期分销海报记录失败：" + e.getMessage();
            log.error(errorMsg, e);
            throw new ServiceException(errorMsg);
        }
    }
}